<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.searchValue"
        class="filter-item"
        clearable
        style="width: 200px;"
        placeholder="请输入标题、内容"
      />
      <el-select
        v-model="listQuery.articleClassId"
        class="filter-item"
        clearable
        style="width: 200px;"
        placeholder="类型"
      >
        <el-option v-for="(item,index) in articleClassList" :key="index" :value="item.id" :label="item.name"/>
      </el-select>
      <el-select
        v-model="listQuery.status"
        class="filter-item"
        clearable
        style="width: 200px;"
        placeholder="状态"
      >
        <el-option v-for="(item,index) in statusData" :key="index" :value="item.code" :label="item.value"/>
      </el-select>
      <el-date-picker
        v-model="date"
        class="filter-item"
        type="daterange"
        style="vertical-align: middle;margin-bottom: 10px;"
        range-separator="至"
        value-format="yyyy-MM-dd"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      />
      <el-button
        v-permission="['article:article:page']"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter">查找
      </el-button>
      <el-button
        v-permission="['article:article:create']"
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate">添加
      </el-button>
      <!-- <el-button
        class="filter-item"
        type="info"
        icon="el-icon-refresh"
        @click="handleRefresh">重置
      </el-button> -->

    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="标题" prop="title"/>

      <el-table-column align="center" label="类型" width="150" prop="name"/>
      <el-table-column align="center" label="封面图片" width="80" prop="imgUrl">
        <template slot-scope="scope">
          <el-popover placement="right" trigger="hover">
            <!--trigger属性值：hover、click、focus 和 manual-->
            <img :src="scope.row.imgUrl" height="230">
            <img slot="reference" :src="scope.row.imgUrl" height="23">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column align="center" label="热度" width="100" prop="heat"/>
      <el-table-column align="center" label="状态" width="150" prop="status">
        <template slot-scope="scope">{{ articleStatus(scope.row.status) }}</template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="200" prop="gmtCreate"/>
      <el-table-column align="center" label="操作" width="300" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-permission="['article:article:show']"
            type="success"
            size="mini"
            @click="handleDetail(scope.row)">查看
          </el-button>
          <el-button
            v-permission="['article:article:edit']"
            v-if="scope.row.status === 0 || scope.row.status === 2 || scope.row.status === 3"
            type="warning"
            size="mini"
            @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button
            v-permission="['article:article:edit']"
            v-if="scope.row.status === 1"
            type="info"
            size="mini"
            @click="handleWithdraw(scope.row)">撤回
          </el-button>
          <el-button
            v-permission="['article:article:issue']"
            v-if="scope.row.status === 0 || scope.row.status === 2 || scope.row.status === 3"
            type="primary"
            size="mini"
            @click="handleIssue(scope.row)">发布
          </el-button>
          <el-button
            v-permission="['article:article:delete']"
            v-if="scope.row.status === 0 || scope.row.status === 3"
            type="danger"
            size="mini"
            @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 详情对话框 -->
    <el-dialog
      v-loading="loading"
      :title="'文章详情'"
      :visible.sync="dialogFormVisible"
      width="1000px"
      @close="dialogClose">
      <div style="text-align: center;font-size: 30px">{{ contentRecord.title }}</div>
      <br>
      <div style="text-align: right;font-size: 10px">
        <span>（发布人：{{ contentRecord.gmtCreateUser }}）</span>
        <span>发布时间：{{ contentRecord.gmtCreate }} </span>
      </div>
      <el-divider style="margin-top: 5px"/>
      <div class="contentRecord">
        <!-- <label v-html="contentRecord.content"/> -->
        <div v-html="contentRecord.content"/>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  pageArticle,
  updateArticle,
  deleteArticle,
  detailArticle,
  issueArticle
} from '@/api/article'
import { pageArticleClass } from '@/api/articleClass'
import { createStorage } from '@/api/storage'
import { getToken } from '@/utils/auth'
import Pagination from '@/components/Pagination'
import Editor from '@tinymce/tinymce-vue' // Secondary package based on el-pagination

const statusData = [{ code: 0, value: '未发布' }, { code: 1, value: '已发布' }, {
  code: 3,
  value: '撤回'
}]
export default {
  name: 'Article',
  components: { Pagination, Editor },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      date: [],
      listQuery: {
        page: 1,
        limit: 20,
        status: undefined,
        name: undefined,
        code: undefined,
        startTime: undefined,
        endTime: undefined
      },
      statusData: statusData,
      articleClassList: [],
      dataForm: {},
      contentRecord: {},
      loading: false,
      dialogFormVisible: false,
      rules: {
        id: [{ required: true, message: 'id不能为空', trigger: 'blur' }],
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        articleClassId: [{ required: true, message: '类型不能为空', trigger: 'blur' }]
      },
      editorInit: {
        language: 'zh_CN',
        convert_urls: false,
        plugins: ['advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'],
        toolbar: ['searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample', 'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'],
        images_upload_handler: function(blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          createStorage(formData).then(res => {
            success(res.data.url)
          }).catch(() => {
            failure('上传失败，请重新上传')
          })
        }
      }
    }
  },
  computed: {
    headers() {
      return {
        ADMINTOKEN: getToken()
      }
    }
  },
  created() {
    this.getList()
    pageArticleClass().then(response => {
      this.articleClassList = response.data.data.items
    })
  },
  methods: {
    getList() {
      this.listLoading = true

      pageArticle(this.listQuery)
        .then(response => {
          console.log(response)
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    // 文章状态显示
    articleStatus(data) {
      if (data === 0) {
        return '未发布'
      } else if (data === 1) {
        return '已发布'
      } else if (data === 2) {
        return '草稿'
      } else if (data === 3) {
        return '撤回'
      }
    },
    handleFilter() {
      if (this.date) {
        this.listQuery.startTime = this.date[0]
        this.listQuery.endTime = this.date[1]
      } else if (!this.date) {
        this.listQuery.startTime = []
        this.listQuery.endTime = []
      }
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {}
    },
    // 添加
    handleCreate() {
      this.$router.push({ path: '/article/addForm' })
    },
    // 重置
    // handleRefresh() {
    //   this.listQuery = {
    //     page: 1,
    //     limit: 20,
    //     status: undefined,
    //     name: undefined,
    //     code: undefined,
    //     startTime: undefined,
    //     endTime: undefined
    //   }
    //   this.date = []
    //   this.getList()
    // },
    // 查看
    handleDetail(row) {
      this.dialogFormVisible = true
      this.loading = true
      detailArticle(row.id).then(response => {
        this.contentRecord = response.data.data
        this.loading = false
      })
    },
    // 编辑
    handleUpdate(row) {
      this.$router.push({ path: '/article/addForm', query: { id: row.id }})
    },
    // 删除
    handleDelete(row) {
      this.$confirm('此操作将永久删除该文章【' + row.title + '】, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteArticle(row.id)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      }).catch(() => {
        return false
      })
    },
    // 撤回
    handleWithdraw(data) {
      // 将状态设置为撤回
      data.status = 3
      updateArticle(data)
        .then(response => {
          this.$notify.success({
            title: '成功',
            message: '撤回成功'
          })
          this.getList()
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
        })
    },
    // 发布
    handleIssue(data) {
      // 将状态设置为发布
      issueArticle(data.id)
        .then(response => {
          this.$notify.success({
            title: '成功',
            message: '发布成功'
          })
          this.getList()
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
        })
    },
    handleCancel() {
      this.dialogFormVisible = false
      this.dataForm.content = undefined
    },
    dialogClose() {
      this.dialogFormVisible = false
      this.loading = false
      this.contentRecord = {}
    }
  }
}
</script>

<style lang="scss" scoped>
.contentRecord{
  ::v-deep img{
    width: 100%;
  }
}
/deep/.el-input__inner {
  line-height: 30px;
}
/deep/.el-date-editor .el-range-separator{
  width: auto;
}
.filter-container {
  //padding-bottom: 10px;
  //display: flex;
  //align-items: center;

  //.filter-item {
  //  display: inline-block;
  //  vertical-align: middle;
  //  margin-bottom: 10px;
  //  padding: 0 10px;
  //}
}

</style>
